/**
 * Copyright (C) 2010-2016 eBusiness Information, Excilys Group
 * Copyright (C) 2016-2020 the AndroidAnnotations project
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed To in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package org.ohosannotations.internal.core.handler;

import com.helger.jcodemodel.JBlock;
import com.helger.jcodemodel.JFieldRef;
import com.helger.jcodemodel.JFieldVar;
import com.helger.jcodemodel.JVar;

import org.ohosannotations.ElementValidation;
import org.ohosannotations.OhosAnnotationsEnvironment;
import org.ohosannotations.annotations.DataBound;
import org.ohosannotations.annotations.EFraction;
import org.ohosannotations.helper.IdValidatorHelper;
import org.ohosannotations.holder.EFractionHolder;
import org.ohosannotations.rclass.IRClass;

import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;

import static com.helger.jcodemodel.JExpr.FALSE;
import static com.helger.jcodemodel.JExpr._null;

/**
 * efraction处理程序
 *
 * @author dev
 * @since 2021-07-22
 */
public class EFractionHandler extends CoreBaseGeneratingAnnotationHandler<EFractionHolder> {
    /**
     * efraction处理程序
     *
     * @param environment 环境
     */
    public EFractionHandler(OhosAnnotationsEnvironment environment) {
        super(EFraction.class, environment);
    }

    /**
     * 创建生成类持有人
     *
     * @param environment 环境
     * @param annotatedElement 带注释的元素
     * @return {@link EFractionHolder}
     * @throws Exception 异常
     */
    @Override
    public EFractionHolder createGeneratedClassHolder(OhosAnnotationsEnvironment environment,
        TypeElement annotatedElement) throws Exception {
        return new EFractionHolder(environment, annotatedElement);
    }

    /**
     * 验证
     *
     * @param element 元素
     * @param validation 验证
     */
    @Override
    public void validate(Element element, ElementValidation validation) {
        super.validate(element, validation);

        validatorHelper.resIdsExist(element, IRClass.Res.LAYOUT,
            IdValidatorHelper.FallbackStrategy.ALLOW_NO_RES_ID, validation);

        validatorHelper.isNotPrivate(element, validation);

        validatorHelper.isAbstractOrHasEmptyConstructor(element, validation);

        validatorHelper.extendsFraction(element, validation);

        coreValidatorHelper.checkDataBoundAnnotation(element, validation);
    }

    /**
     * 过程
     *
     * @param element 元素
     * @param holder 持有人
     */
    @Override
    public void process(Element element, EFractionHolder holder) {
        JFieldRef contentViewId = annotationHelper.extractOneAnnotationFieldRef(element, IRClass.Res.LAYOUT, false);

        if (contentViewId == null) {
            return;
        }

        JBlock block = holder.getOnCreateAfterSuperBlock();
        JVar scatter = holder.getScatter();
        JVar container = holder.getContainer();

        JFieldVar contentView = holder.getContentComponent();

        boolean isForceInjection = element.getAnnotation(EFraction.class).forceLayoutInjection();

        JBlock inflationBlock;

        if (!isForceInjection) {
            inflationBlock = block._if(contentView.eq(_null())) //
                ._then();
        } else {
            inflationBlock = block;
        }

        if (element.getAnnotation(DataBound.class) != null) {
            JFieldVar bindingField = holder.getDataBindingField();
            inflationBlock.assign(bindingField,
                holder.getDataBindingInflationExpression(contentViewId, container, false));
            inflationBlock.assign(contentView, bindingField.invoke("getRoot"));
            holder.getOnDestroyBeforeSuperBlock().invoke(bindingField, "unbind");
            holder.clearInjectedView(bindingField);
        } else {
            inflationBlock.assign(contentView, scatter.invoke("parse").arg(contentViewId).arg(container).arg(FALSE));
        }
    }
}
